package org.easy.byteasr;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ConcurrentHashMap;

@Data
@AllArgsConstructor
public class ByteRealtimeAsrV2Template {

    private static ConcurrentHashMap<String, ByteAsrV2Client> registry = new ConcurrentHashMap<>();

    private String appId;
    private String token;
    private String cluster;

    public void init(String userId) {
        ByteAsrV2Client asr_client = ByteAsrV2Client.build();
        asr_client.setAppid(appId);
        asr_client.setToken(token);
        asr_client.setCluster(cluster);
        asr_client.setFormat("wav");
        asr_client.setShow_utterances(true);
        try {
            asr_client.asr_sync_connect();
        } catch (IOException | InterruptedException | NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        registry.put(userId, asr_client);
    }

    public String working(String userId, byte[] audio, boolean is_last) {
        ByteAsrV2Client byteAsrV2Client = registry.get(userId);
        try {

            AsrResponse asrResponse = byteAsrV2Client.asr_send(audio, is_last);
            if (asrResponse.getResult() == null) {
                return null;
            }

            AsrResponse.Result[] result = asrResponse.getResult();
            AsrResponse.Result result1 = result[0];
            return result1.getText();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void finish(String userId) {
        ByteAsrV2Client byteAsrV2Client = registry.get(userId);
        if (byteAsrV2Client == null) {
            return;
        }
        byteAsrV2Client.asr_close();
    }


}
